package com.cyf.service.impl;

import com.cyf.db.bean.AppCar;
import com.cyf.db.bean.User;
import com.cyf.db.mapper.AppCarMapper;
import com.cyf.db.mapper.AppUserCarMapper;
import com.cyf.service.AppUserCarService;
import com.cyf.service.bean.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by hfy on 2017/6/8.
 */
@Service
public class AppUserCarServiceImpl implements AppUserCarService {
    private static final Logger logger = LoggerFactory.getLogger(AppUserCarServiceImpl.class);

    @Autowired
    private AppUserCarMapper appUserCarMapper;
    @Autowired
    private AppCarMapper appCarMapper;

    @Override
    public void addCar(User user, AppCar car) throws CustomException {
        List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
        int carCount = null == appCars ? 0 : appCars.size();
        if (null != appCars) {
            for (AppCar appCar : appCars) {
                if (car.getPlate().equals(appCar.getPlate())) {
                    return;
                }
            }
        }
        // TODO: 2018/1/12 因丰和顺市场，此处代码注释
//        if (carCount == 3) {
//            throw new CustomException("用户车辆已达上限！");
//        }
        AppCar appCar = appCarMapper.getByPlate(car.getPlate());
        if (appCar == null) {
            appCar = new AppCar(car.getPlate());
            appCar.setType(car.getType());
            appCar.setColor(car.getColor());
            appCar.setBrand(car.getBrand());
            appCarMapper.insertAppCar(appCar);
        }
        appUserCarMapper.insertUserCar(user.getId(), appCar.getId());
    }

    @Override
    public String selectByPlate(String plate) {
        return appUserCarMapper.selectByPlate(plate);
    }
}
